package net.wanglu.www.zzz.service.se.obj;

import java.util.Collection;
import java.util.HashMap;
import java.util.regex.Pattern;

import net.wanglu.www.zzz.service._Service;

import org.apache.commons.lang3.tuple.Pair;

import edu.stanford.nlp.trees.EnglishGrammaticalRelations;
import edu.stanford.nlp.trees.GrammaticalRelation;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeGraphNode;
import edu.stanford.nlp.trees.TypedDependency;
import edu.stanford.nlp.trees.tregex.TregexMatcher;
import edu.stanford.nlp.trees.tregex.TregexPattern;

public class PObjExtracter extends _Service {

	@Override
	public Object service(Object... objects) throws Exception {
		// TODO Auto-generated method stub
		HashMap<?, ?> preprocessData = (HashMap<?, ?>) objects[0];
		TypedDependency pobj = (TypedDependency) objects[1];

		Tree root = (Tree) preprocessData.get("root");
		Collection<?> tdl = (Collection<?>) preprocessData.get("tdl");
		
		TypedDependency prep = null;
		for ( Object obj : tdl) {
			TypedDependency TD = (TypedDependency) obj;
			GrammaticalRelation reln = TD.reln();

			if ( reln.equals(EnglishGrammaticalRelations.PREPOSITIONAL_MODIFIER)) {
				if ( pobj.gov().toString().equals(TD.dep().toString())) {
					prep = TD;
					break;
				}
			}
		}

		Tree objectiveAncestor = null;
		Tree objectGovAncestor = null;
		sb.clear();
		sb.append("/\\bPP\\b|\\bWHPP\\b/");
		sb.append("<");
		sb.append("(");
		sb.append("/").append(Pattern.quote(prep.dep().label().tag())).append("/").append("<");
		sb.append("/").append(Pattern.quote(prep.dep().label().word())).append("/");
		sb.append(")");
		TregexPattern pattern = TregexPattern.compile(sb.toString());
		TregexMatcher matcher = pattern.matcher(root);
		if ( matcher.find()) {
			objectGovAncestor = matcher.getMatch();
			objectiveAncestor = objectGovAncestor;
		}
		
		final TreeGraphNode fobject = pobj.dep();
		final TreeGraphNode fobjectGov = pobj.gov();
		final Tree fobjectiveAncestor = objectiveAncestor;
		final Tree fobjectGovAncestor = objectGovAncestor;
		final String frelation = pobj.reln().getShortName();
		final TreeGraphNode fheadword = prep.gov();
		return new _ObjectTuple() {
			{
				this.setObject(fobject);
				this.setObjectAncestor(fobjectiveAncestor);
				this.setObjectGov(fobjectGov);
				this.setObjectGovAncestor(fobjectGovAncestor);
				this.setRelation(frelation);
			}
			@Override
			public Object customize() throws Exception {
				// TODO Auto-generated method stub
				return Pair.of(fheadword, null);
			}
		};
	}
}
